package com.lingrit.provider.filter;

import com.lingrit.provider.config.SysProperties;
import com.lingrit.provider.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author qlkj
 */
public class TokenFilter extends GenericFilterBean {

    @Autowired
    private SysProperties sysProperties;

    @Autowired
    private TokenUtils tokenUtils;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;

        // todo 验证token
        if (StringUtils.equalsAny(request.getRequestURI(),sysProperties.getExcludedUris() ) && sysProperties.getRegisterSwitch()) {
            // 注册没有token，跳过
            chain.doFilter(req, res);
        } else {
            //得到请求头信息authorization信息
            final String fpTokenHeader = request.getHeader("fpToken");
            tokenUtils.parseToken(fpTokenHeader);
            chain.doFilter(req, res);
        }
    }
}
